<template>
  <view class="container">
    <view class="title">人脸认证</view>

    <!-- 预览区域 -->
    <view v-if="previewImage" class="image-preview">
      <image :src="previewImage" mode="aspectFit" class="preview-img"></image>
    </view>

    <view v-else class="placeholder" @click="chooseImage">
      <text class="icon">📷</text>
      <text class="tip">点击上传人脸照片</text>
    </view>

    <!-- 操作按钮 -->
    <button class="btn" :disabled="!previewImage || uploading" @tap="uploadImage">
      {{ uploading ? '上传中...' : '开始人脸认证' }}
    </button>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { verifyDriverFaceAPI } from '@/services/home'
import type { DriverFaceModelForm } from '@/types/home'

import { parseQueryString } from '@/utils/http'
import type { TokenResult } from '@/types/member'
import {
  postLoginWxMinAPI,
  postDriverLoginWxMinAPI,
  postUserinfoAPI,
  driverUserinfoAPI,
} from '@/services/login'
import { onLoad } from '@dcloudio/uni-app'
import { useMemberStore, useDriverStore } from '@/stores'

// 保存会员信息
const memberStore = useMemberStore()

// 响应式数据
const previewImage = ref('')
const imageBase64 = ref('' as string)
const uploading = ref(false)
const query = defineProps<{
  openId: string
  sessionKey: string
}>()
const openId = ref(query.openId as any)
const sessionKey = ref(query.sessionKey as any)

// 1. 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sourceType: ['camera', 'album'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]
      previewImage.value = tempFilePath
      await convertImageToBase64(tempFilePath)
    },
    fail: (err) => {
      if (!err.errMsg.includes('cancel')) {
        uni.showToast({ title: '选择图片失败', icon: 'none' })
      }
    },
  })
}

// 2. 将图片转为 Base64（兼容小程序和 H5）
const convertImageToBase64 = (tempFilePath: any) => {
  return new Promise((resolve, reject) => {
    if (uni.getFileSystemManager) {
      // 小程序平台
      const fs = uni.getFileSystemManager()
      fs.readFile({
        filePath: tempFilePath,
        encoding: 'base64',
        success: (res: any) => {
          imageBase64.value = res.data
          resolve(res.data)
        },
        fail: (err) => {
          uni.showToast({ title: '读取图片失败', icon: 'none' })
          reject(err)
        },
      })
    }
  })
}

// 3. 上传并创建人脸模型
const uploadImage = async () => {
  const res = await uni.getUserProfile({
    desc: '用于完善会员资料',
  })

  const { encryptedData, iv } = res
  if (!imageBase64.value) {
    uni.showToast({ title: '请先选择照片', icon: 'none' })
    return
  }

  // 获取openId
  if (openId.value === 'null' || sessionKey.value === 'null') {
    memberStore.clearProfile()
    const codeRes = await wx.login()
    const res = await postDriverLoginWxMinAPI({ code: codeRes.code })
    memberStore.setProfile(res.data)
    // 获取用户信息
    openId.value = res.data.openId
    sessionKey.value = res.data.sessionKey
  }
  // await driverUserinfo(encryptedData, iv, openId.value, sessionKey.value)
  // return
  uploading.value = true

  const params: DriverFaceModelForm = {
    openId: openId.value,
    imageBase64: imageBase64.value,
  }

  const aa = await verifyDriverFaceAPI(params)
  if (aa.data) {
    await driverUserinfo(encryptedData, iv, openId.value, sessionKey.value)
    uni.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 2000,
    })
  }
}

const driverUserinfo = async (encryptedData: any, iv: any, openId: string, sessionKey: string) => {
  // 将 encryptedData 和 iv 发送到后端解密
  const response = await driverUserinfoAPI({ encryptedData, iv, openId, sessionKey })
  console.log('用户信息:', response.data)
  memberStore.setUserInfo(response.data)
  uni.switchTab({
    url: '/pages/home/home',
  })
}
</script>

<style scoped>
.container {
  padding: 40rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 60rpx;
  color: #333;
}

.placeholder {
  width: 80%;
  height: 400rpx;
  margin: 0 auto 60rpx;
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #fafafa;
  color: #999;
}

.icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.tip {
  font-size: 28rpx;
}

.image-preview {
  width: 80%;
  height: 400rpx;
  margin: 0 auto 60rpx;
  overflow: hidden;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.preview-img {
  width: 100%;
  height: 100%;
}

.btn {
  width: 80%;
  margin: 0 auto;
  background-color: #007aff;
  color: #fff;
  font-size: 32rpx;
  border-radius: 80rpx;
}

.btn:disabled {
  background-color: #ccc;
}
</style>
